#include "DataSupplier.h"

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <math.h>

#include "boost\lambda\lambda.hpp"

DataSupplier::DataSupplier(void)
{
    m_currIdx = 0;
    m_isInited = false;
    m_fileName = NULL;
    m_ID.clear();
    m_CX.clear();
    m_CY.clear();
    m_Act.clear();
    m_SD.clear();
}

/*static*/ DataSupplier* DataSupplier::ms_instance = NULL;

/*static*/ DataSupplier* DataSupplier::S()
{
    if (NULL==ms_instance)
    {
        ms_instance = new DataSupplier();
    }
    return ms_instance;
}

/*static*/ void DataSupplier::Destory()
{
    if (NULL!=ms_instance)
    {
        delete ms_instance;
        ms_instance = NULL;
    }
}

bool DataSupplier::InitFromFile( const wchar_t* p_fl )
{
	std::ifstream inf( p_fl, std::ifstream::in );
	if ( !inf.is_open() )
	{
        //OutputDebugString("Oooops..... Failed to open the "+p_fl+"\n");
		std::cerr<<"Oooops..... Failed to open the "<<p_fl<<"\n";
        return false;
	}
    
    ClearData();
    m_currIdx = 0;

    unsigned int    frameID = 0;
    double          schoalX = 0.0;
    double          schoalY = 0.0;
    double          schoalAct = 0.0;
    double          schoalSD = 0.0;

	//read in file
	while ( !inf.eof() )
	{
        inf>>frameID>>schoalX>>schoalY>>schoalAct>>schoalSD;

        if ( frameID==0 )
        {
            //false reading
            ClearData();
            return false;
        }

        m_ID.push_back(frameID);
        m_CX.push_back(schoalX);
        m_CY.push_back(schoalY);
        m_Act.push_back(schoalAct);
        m_SD.push_back(schoalSD);
	}
    inf.close();

    PreProcessing();

    m_isInited = true;

    return true;
}

double DataSupplier::QueryTime()
{
    return (double)m_currIdx/600.0;
}

double DataSupplier::QueryPTime()
{
    UINT idx = m_currIdx - m_ID.size()/2;
    if ( idx < 0.0 )
    {
        return 0.0;
    }

    return (double)idx/600.0;
}

void DataSupplier::PreProcessing()
{
}

UINT DataSupplier::PeekData( dVec& pData )
{
    if ( m_ID.empty() || m_ID.size()==m_currIdx )
    {
        return -1;
    }

    pData.clear();

    pData.push_back(m_CX[m_currIdx]);
    pData.push_back(m_CY[m_currIdx]);
    pData.push_back(m_Act[m_currIdx]);
    pData.push_back(m_SD[m_currIdx]);

    return m_ID[m_currIdx++];
}

bool DataSupplier::IsEOF() const
{
    return m_currIdx==m_ID.size();
}

void DataSupplier::ClearData()
{
    m_ID.clear();
    m_CX.clear();
    m_CY.clear();
    m_Act.clear();
    m_SD.clear();
}

/*virtual*/ DataSupplier::~DataSupplier(void)
{
    ClearData();
}



